package servicex

import (
	"bytes"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/skip2/go-qrcode"
	"zhonghui/console/warehouse/helperx"
)

// MakeQrCode 生成png格式的二维码
// size为图片像素尺寸
// bestRecoveryLevel传递true则二维码误差率30%，false则为15%
func MakeQrCode(content string, size int, bestRecoveryLevel bool) ([]byte, error) {
	level := qrcode.Highest
	if !bestRecoveryLevel {
		level = qrcode.Medium
	}

	return qrcode.Encode(content, level, size)
}

// MakeQrCodeAndUpload 生成二维码并上传，返回OSS相对地址，之后可以自行拼域名，建议数据库中只存储相对地址
// path 为自定义上传路径，首尾不能有/，可传递如 test1/test2
func MakeQrCodeAndUpload(content string, size int, bestRecoveryLevel bool, path string) (string, error) {
	png, err := MakeQrCode(content, size, bestRecoveryLevel)
	if err != nil {
		return "", err
	}

	fileName := fmt.Sprintf("%s.png", helperx.RandomString(32))

	// 默认上传路径
	objectPath := fmt.Sprintf("zh/qrcode/%s/%s", time.Now().Format(helperx.TimeLayoutYmd), fileName)
	// 自定义上传路径
	if path != "" {
		if strings.HasPrefix(path, "/") || strings.HasSuffix(path, "/") {
			return "", errors.New("the beginning and end of path cannot have /")
		}

		objectPath = fmt.Sprintf("%s/%s", path, fileName)
	}

	oc, err := OssClient("main")
	if err != nil {
		return "", err
	}

	if err := oc.OssPutBucket(objectPath, bytes.NewReader(png)); err != nil {
		return "", err
	}

	return objectPath, nil
}
